package com.czp.infosharingplatformapp.controller;

import com.czp.infosharingplatformapp.dto.CategoryResponse;
import com.czp.infosharingplatformapp.dto.ResourceResponse;
import com.czp.infosharingplatformapp.model.Category;
import com.czp.infosharingplatformapp.model.Resource;
import com.czp.infosharingplatformapp.service.CategoryService;
import com.czp.infosharingplatformapp.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/resources")
public class ResourceController {

    @Autowired
    private ResourceService resourceService;

    @PostMapping("/upload")
    public ResourceResponse uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("description") String description,
            @RequestParam("categoryId") Long categoryId,
            @RequestParam("uploaderId") Long uploaderId) throws IOException {

        Resource resource =  resourceService.saveResource(file, description, categoryId, uploaderId);
        return resourceService.convertToResourceResponse(resource);
    }

    // 下载文件的接口
    @GetMapping("/{id}")
    public ResponseEntity<InputStreamResource> downloadFile(@PathVariable Long id) throws IOException {
        // 根据文件 ID 获取文件信息
        com.czp.infosharingplatformapp.model.Resource resource = resourceService.findById(id);

        // 获取文件路径
        File file = new File(resource.getFilePath());
        if (!file.exists()) {
            throw new RuntimeException("文件不存在！");
        }

        // 读取文件数据
        InputStreamResource fileStream = new InputStreamResource(new FileInputStream(file));

        // 对文件名进行 URL 编码，确保其兼容 HTTP 协议
        String encodedFileName = URLEncoder.encode(resource.getFileName(), StandardCharsets.UTF_8)
                .replace("+", "%20"); // 替换 "+" 为 "%20"，以符合 URL 规范

        // 构造响应
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM) // 设置为文件流
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + encodedFileName) // 确保支持 RFC 8187 的编码
                .body(fileStream);
    }

    @GetMapping("/search")
    public List<ResourceResponse> searchFiles(@RequestParam("keyword") String keyword) {
        return resourceService.searchByFileName(keyword).stream()
                .map(resourceService::convertToResourceResponse)
                .collect(Collectors.toList());
    }

    @GetMapping("/filter")
    public List<ResourceResponse> filterFilesByCategory(@RequestParam("categoryId") Long categoryId) {
        return resourceService.filterByCategory(categoryId).stream()
                .map(resourceService::convertToResourceResponse)
                .collect(Collectors.toList());
    }

    @GetMapping("/all")
    public List<ResourceResponse> getAllResources() {
        return resourceService.getAllResources().stream()
                .map(resourceService::convertToResourceResponse)
                .collect(Collectors.toList());
    }

    @DeleteMapping("/{resourceId}")
    public String deleteResource(@PathVariable Long resourceId) {
        resourceService.deleteResource(resourceId);
        return "资源已成功删除";
    }
}